const { app, BrowserWindow, ipcMain, Notification, nativeImage, Tray, Menu } = require("electron");
const path = require("node:path");

// 设置一个应用用户模型 ID (AppUserModelID)。
// 这个 ID 将用于在 Windows 任务栏和系统通知中显示应用名称。
app.setAppUserModelId("番茄钟");

let win;
const createWindow = () => {
    win = new BrowserWindow({
        width: 300,
        height: 400,
        // x: 1500,
        // y: 200,
        // alwaysOnTop: true,
        frame: false,
        backgroundColor: "#f82121",
        icon: path.join(__dirname, "img/tomato.png"),
        webPreferences: {
            // nodeIntegration: true,
            // contextIsolation: false,
            preload: path.join(__dirname, "preload.js")
        }
    });

    win.loadFile(path.resolve(__dirname, "index.html"));

    // win.webContents.toggleDevTools();
};

// 监听按键事件
const handleKeyUp = (event, input) => {
    // 按Esc键退出全屏
    if (input.type === "keyUp" && input.key === "Escape") {
        if (win.isFullScreen()) {
            win.setFullScreen(false);
            win.webContents.off("before-input-event", handleKeyUp);
        }
        event.preventDefault();
    }
};

const icon = nativeImage.createFromPath(path.join(__dirname, "img/tomato.png"));
const createTray = () => {
    const tray = new Tray(icon);

    // 托盘菜单
    const contextMenu = Menu.buildFromTemplate([
        {
            label: "全屏",
            role: "togglefullscreen",
            click: () => {
                if (!win.isFullScreen()) {
                    win.webContents.on("before-input-event", handleKeyUp);
                    win.setFullScreen(true);
                } else {
                    win.setFullScreen(false);
                    win.webContents.off("before-input-event", handleKeyUp);
                }
            }
        },
        { label: "最小化", role: "close", click: () => (win.isVisible() ? win.hide() : "") },
        { label: "退出", role: "quit" }
    ]);
    tray.setContextMenu(contextMenu);

    // 托盘图标文本
    tray.setToolTip("番茄钟"); // Windows
    tray.setTitle("番茄钟"); // mac

    // 托盘点击
    tray.on("click", e => {
        if (e.metaKey) {
            win.isVisible() ? win.hide() : win.show();
        } else {
            win.isVisible() ? win.hide() : win.show();
        }
    });
};

const notificationForMacOS = (signal, countLoop) => {
    // 用 promise 将返回结果包一下
    return new Promise(resolve => {
        // 创建系统通知
        const notification = new Notification({
            title: "到点啦！",
            body: "想要休息吗？",
            actions: [
                {
                    text: "开始休息",
                    type: "button"
                }
            ],
            closeButtonText: "继续工作"
        });

        notification.show();
        notification.on("action", () => {
            resolve("rest");
        });
        notification.on("close", () => {
            resolve("work");
        });
    });
};

const emojes = {
    // work: "🍅",
    work: "😃",
    rest: "😎",
    over: "💀",
    long_rest: "🏃",
    again_work: "💪",
    count: {
        1: "①",
        2: "②",
        3: "③",
        4: "④"
    }
};
const notificationForWindows = (signal, countLoop) => {
    let title = `第 ${emojes.count[countLoop]} 个工作周期`;
    let body =
        signal === "rest" ? `休息时间结束了，继续加油吧！${emojes.work}` : `工作时间结束了，该休息啦！${emojes.rest}`;
    if (signal === "work" && countLoop === 4) {
        title = "休息 30 分钟";
        body = `已经工作很久了，出去走走吧！${emojes.long_rest} `;
    } else if (signal === "work" && countLoop > 4) {
        title = `${emojes.over}${emojes.over}${emojes.over}`;
        body = "是时候休息啦！！！";
    } else if (signal === "rest" && countLoop === 0) {
        title = "休息完毕";
        body = `继续大展身手吧！${emojes.again_work}`;
    }
    return new Promise(resolve => {
        new Notification({
            title,
            body,
            icon: icon
        }).show();
        resolve("noSignal");
    });
};

const handleIPC = () => {
    ipcMain.handle("time-up-notification", async (_, signal, countLoop) => {
        let res;
        if (process.platform === "darwin") {
            res = await notificationForMacOS(signal, countLoop);
        } else {
            res = await notificationForWindows(signal, countLoop);
        }
        return res;
    });
};

app.whenReady().then(() => {
    // console.log("App is ready!");
    createWindow();

    createTray();

    // 处理 IPC
    handleIPC();

    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on("window-all-closed", () => {
    if (process.platform !== "darwin") app.quit();
});
